import { Button, View, Text } from "@tarojs/components";
import { useEffect, useState, useCallback, useMemo } from "react";
// eslint-disable-next-line import/first
import { Gem as GemType } from '@/types/global';
import "./index.less";

interface GemModelProps {
  close: () => void;
  gemSource?: GemType[]; // 初始宝石列表
  gemPosition?: string[]; // 宝石在宝石盘的位置 存储宝石id 若为空则为-1
  currentPlayerIp?: string; // 当前玩家IP
  onTakeGems?: (playerIp: string, gemPositionIndices: number[]) => void; // 拿取宝石的回调函数
  maxGemsToTake?: number; // 最多可以拿取的宝石数量，默认为3
  allowedGemColors?: string[]; // 允许拿取的宝石颜色，如果未指定则允许所有颜色
}

export default function GemModal({ 
  close, 
  gemSource, 
  gemPosition, 
  currentPlayerIp, 
  onTakeGems,
  maxGemsToTake = 3,
  allowedGemColors = ['red', 'blue', 'green', 'white', 'black', 'pink'] // 默认除了金色以外的颜色
}: GemModelProps) {
  const rows = 5;
  const cols = 5;
  const [selectedGemList, setSelectedGemList] = useState<number[]>([]); // 存储索引
  const [gemPositionList, setGemPositionList] = useState<string[]>([]); // 存储宝石ID

  // 获取宝石源数据
  const getGemSource = (): GemType[] => {
    if (gemSource && gemSource.length > 0) {
      return gemSource;
    }
    
    // 默认宝石数据
    return [
      { id: "1", color: 'red' },
      { id: "2", color: 'red' },
      { id: "3", color: 'red' },
      { id: "4", color: 'red' },
      { id: "5", color: 'blue' },
      { id: "6", color: 'blue' },
      { id: "7", color: 'blue' },
      { id: "8", color: 'blue' },
      { id: "9", color: 'green' },
      { id: "10", color: 'green' },
      { id: "11", color: 'green' },
      { id: '12', color: 'green' },
      { id: "13", color: 'gold' },
      { id: "14", color: 'gold' },
      { id: "15", color: 'gold' },
      { id: "16", color: 'black' },
      { id: "17", color: 'black' },
      { id: "18", color: 'black' },
      { id: "19", color: 'black' },
      { id: "20", color: 'white' },
      { id: "21", color: 'white' },
      { id: "22", color: 'white' },
      { id: "23", color: 'white' },
      { id: "24", color: 'pink' },
      { id: "25", color: 'pink' },
    ];
  };

  // 获取宝石位置数据
  const getGemPosition = (): string[] => {
    if (gemPosition && gemPosition.length > 0) {
      return gemPosition;
    }
    return gemPositionList;
  };

  const currentGemSource = getGemSource();
  const currentGemPosition = getGemPosition();

  useEffect(() => {
    // 生成默认的宝石位置数组，存储宝石ID而不是索引
    const initialPositions = currentGemSource.map(gem => gem.id);
    setGemPositionList(initialPositions);
  }, [currentGemSource]);

  // 获取宝石的行和列
  const getRowCol = useCallback((index: number) => {
    return {
      row: Math.floor(index / cols),
      col: index % cols
    };
  }, [cols]);

  // 检查两个宝石是否在同一直线上（横、竖、斜）
  const areGemsInLine = useCallback((index1: number, index2: number) => {
    const pos1 = getRowCol(index1);
    const pos2 = getRowCol(index2);
    
    // 水平线
    if (pos1.row === pos2.row) return true;
    // 垂直线
    if (pos1.col === pos2.col) return true;
    // 对角线
    if (Math.abs(pos1.row - pos2.row) === Math.abs(pos1.col - pos2.col)) return true;
    
    return false;
  }, [getRowCol]);

  // 计算两个宝石之间的方向向量
  const getDirection = useCallback((index1: number, index2: number) => {
    const pos1 = getRowCol(index1);
    const pos2 = getRowCol(index2);
    
    const dr = pos2.row - pos1.row;
    const dc = pos2.col - pos1.col;
    
    // 标准化方向向量
    if (dr === 0 && dc === 0) return { dr: 0, dc: 0 };
    
    const gcd = (a: number, b: number) => {
      a = Math.abs(a);
      b = Math.abs(b);
      if (b === 0) return a;
      return gcd(b, a % b);
    };
    
    const g = gcd(dr, dc);
    
    return {
      dr: dr / g,
      dc: dc / g
    };
  }, [getRowCol]);

  // 获取两个宝石之间的所有宝石索引（不包括端点）
  const getGemsBetween = useCallback((index1: number, index2: number) => {
    if (!areGemsInLine(index1, index2)) return [];
    
    const direction = getDirection(index1, index2);
    if (direction.dr === 0 && direction.dc === 0) return [];
    
    const result: number[] = [];
    let currentRow = getRowCol(index1).row + direction.dr;
    let currentCol = getRowCol(index1).col + direction.dc;
    const endPos = getRowCol(index2);
    
    while (currentRow !== endPos.row || currentCol !== endPos.col) {
      result.push(currentRow * cols + currentCol);
      currentRow += direction.dr;
      currentCol += direction.dc;
    }
    
    return result;
  }, [areGemsInLine, getDirection, getRowCol, cols]);

  // 检查一系列宝石是否在同一条直线上，并且连续（没有被隔离宝石阻挡）
  const areGemsInStraightLine = useCallback((indices: number[]) => {
    if (indices.length <= 1) return true;
    if (indices.length === 2) {
      // 检查两个宝石之间是否有隔离宝石阻挡
      const between = getGemsBetween(indices[0], indices[1]);
      for (const index of between) {
        // 检查gemId是否为"-1"（表示空位）
        const gemId = currentGemPosition[index];
        if (gemId === "-1") continue; // 空位不影响连线
        // 根据宝石ID在gemSource数组中查找对应的宝石
        const gem = currentGemSource.find(g => g.id === gemId);
        // 将不在allowedGemColors数组中的颜色作为隔离宝石
        if (gem && !allowedGemColors.includes(gem.color)) {
          return false;
        }
      }
      return areGemsInLine(indices[0], indices[1]);
    }
    
    // 对索引进行排序
    const sortedIndices = [...indices].sort((a, b) => {
      const posA = getRowCol(a);
      const posB = getRowCol(b);
      if (posA.row !== posB.row) return posA.row - posB.row;
      return posA.col - posB.col;
    });
    
    // 对于多个宝石，需要确保它们是连续的
    // 首先检查是否在同一条直线上
    const direction = getDirection(sortedIndices[0], sortedIndices[1]);
    
    // 检查所有宝石是否在同一条直线上
    for (let i = 0; i < sortedIndices.length - 1; i++) {
      const dir = getDirection(sortedIndices[i], sortedIndices[i + 1]);
      if (dir.dr !== direction.dr || dir.dc !== direction.dc) {
        return false;
      }
    }
    
    // 检查宝石是否连续（中间没有未选择的宝石）
    for (let i = 0; i < sortedIndices.length - 1; i++) {
      const current = sortedIndices[i];
      const next = sortedIndices[i + 1];
      
      // 获取两个宝石之间的所有宝石
      const between = getGemsBetween(current, next);
      
      // 检查是否有未选择的宝石（除了空位）
      for (const index of between) {
        const gemId = currentGemPosition[index];
        // 空位不影响连续性
        if (gemId === "-1") continue;
        
        // 如果这个位置的宝石没有被选中，则不连续
        if (!sortedIndices.includes(index)) {
          return false;
        }
        
        // 检查这个位置的宝石是否是隔离宝石
        const gem = currentGemSource.find(g => g.id === gemId);
        if (gem && !allowedGemColors.includes(gem.color)) {
          return false;
        }
      }
    }
    
    return true;
  }, [currentGemSource, currentGemPosition, getGemsBetween, areGemsInLine, getDirection, getRowCol, allowedGemColors]);

  const handleGemClick = useCallback((gemIndex: number) => {
    setSelectedGemList(prev => {
      // 如果点击已选中的宝石，取消选择
      if (prev.includes(gemIndex)) {
        return prev.filter(id => id !== gemIndex);
      }

      // 检查是否选择了无效位置
      const gemId = currentGemPosition[gemIndex];
      // 检查gemId是否为"-1"（表示空位）
      if (gemId === "-1") return prev;
      // 根据宝石ID在gemSource数组中查找对应的宝石
      const gem = currentGemSource.find(g => g.id === gemId);
      
      // 检查宝石颜色是否被允许
      if (allowedGemColors && gem && !allowedGemColors.includes(gem.color)) {
        return prev;
      }
      
      // 不再特别排除金色宝石，而是根据allowedGemColors来判断
      // if (gem?.color === "gold") {
      //   return prev;
      // }

      // 添加新宝石到选择列表
      const newSelection = [...prev, gemIndex];

      // 检查选择数量是否超过限制
      if (newSelection.length > maxGemsToTake) {
        return prev;
      }

      // 检查是否在同一条直线上且没有被隔离宝石阻挡
      if (areGemsInStraightLine(newSelection)) {
        return newSelection;
      }

      return prev;
    });
  }, [currentGemSource, currentGemPosition, areGemsInStraightLine, maxGemsToTake, allowedGemColors]);
  
  const handleConfirmSelection = useCallback(() => {
    if (selectedGemList.length === 0) {
      console.log("没有选择任何宝石");
      return;
    }
    
    console.log("已选择的宝石索引:", selectedGemList);
    
    // 发送拿取宝石的指令
    if (onTakeGems && currentPlayerIp) {
      onTakeGems(currentPlayerIp, selectedGemList);
    }
    
    setSelectedGemList([]);
    close();
  }, [selectedGemList, close, onTakeGems, currentPlayerIp]);

  const handleResetSelection = useCallback(() => {
    setSelectedGemList([]);
  }, []);

  // 获取选中宝石的颜色列表（使用useMemo优化）
  const selectedGemColors = useMemo(() => {
    return selectedGemList.map(index => {
      const gemId = currentGemPosition[index];
      // 检查gemId是否为"-1"（表示空位）
      if (gemId === "-1") return "空位";
      // 根据宝石ID在gemSource数组中查找对应的宝石
      const gem = currentGemSource.find(g => g.id === gemId);
      return gem ? gem.color : "未知";
    });
  }, [selectedGemList, currentGemPosition, currentGemSource]);

  // 优化宝石网格渲染
  const renderGemGrid = useMemo(() => {
    return Array.from({ length: rows }).map((_, rowIndex) => (
      <View key={`row-${rowIndex}`} className='grid-row'>
        {Array.from({ length: cols }).map((__, colIndex) => {
          const gemIndex = rowIndex * cols + colIndex;
          const gemId = currentGemPosition[gemIndex];
          const isSelected = selectedGemList.includes(gemIndex);
          // 当gemId为"-1"时，表示该位置没有宝石，应该显示为空白
          // 根据宝石ID在gemSource数组中查找对应的宝石
          const gem = gemId !== "-1" ? currentGemSource.find(g => g.id === gemId) : null;
          const gemColor = gem ? gem.color : "empty";
          
          // 检查宝石颜色是否被允许
          const isAllowed = !allowedGemColors || allowedGemColors.includes(gemColor);
          const selectionIndex = selectedGemList.indexOf(gemIndex) + 1;

          return (
            <View
              key={`gem-${gemIndex}`} // 使用唯一标识符作为key
              className={`grid-cell ${isSelected ? "selected" : ""} ${gemColor}-gem ${!isAllowed ? "disabled" : ""}`}
              onClick={() => handleGemClick(gemIndex)}
            >
              {isSelected && (
                <View className='selectedIndicator'>
                  <Text className='selectedNumber'>{selectionIndex}</Text>
                </View>
              )}
            </View>
          );
        })}
      </View>
    ));
  }, [rows, cols, currentGemPosition, selectedGemList, currentGemSource, handleGemClick, allowedGemColors]);

  return (
    <View className='gemModelContainer'>
      <View className='gemModelHeader'>
        <Text className='headerTitle'>选择宝石</Text>
        <Text className='headerSubtitle'>请选择1-{maxGemsToTake}个相连的宝石</Text>
      </View>
      
      <View className='gemList'>
        {renderGemGrid}
      </View>

      <View className='selectionInfo'>
        <View className='selectionCount'>
          <Text>已选择: </Text>
          <Text className='countNumber'>{selectedGemList.length}</Text>
          <Text>/{maxGemsToTake} 个宝石</Text>
        </View>
        <View className='selectionColors'>
          {selectedGemColors.map((color, index) => (
            <View key={`color-${index}`} className={`colorBadge ${color}-badge`}>
              <Text>{color}</Text>
            </View>
          ))}
        </View>
      </View>

      <View className='btns'>
        <Button className='actionBtn confirmBtn' onClick={handleConfirmSelection}>确认选择</Button>
        <Button className='actionBtn resetBtn' onClick={handleResetSelection}>重置</Button>
        <Button className='actionBtn closeBtn' onClick={close}>关闭</Button>
      </View>
    </View>
  );
}